package com.shunwang.errors.engine.builder.annotation;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import com.shunwang.errors.engine.builder.LoggerParser;
import com.shunwang.errors.engine.core.ErrorsHandler;
import com.shunwang.errors.engine.util.AnnotationUtil;
import com.shunwang.errors.engine.util.ClazzUtil;
import com.shunwang.errors.exception.ParserException;

public abstract class LoggerAnnotationParser extends LoggerParser{

	private File file;
	
	private List<String> classList = new ArrayList<String>();
	
	private static final String suff = ".class";
	
	public LoggerAnnotationParser(File file){
		this.file = file;
	}
	
	public LoggerAnnotationParser(String filePath){
		File file = new File(filePath);
		if(!file.exists()){
			throw new NullPointerException("file path:"+filePath +" not exists");
		}
		this.file = file;
	}

	@Override
	public void parserData() throws IOException, ParserException {
		String path = file.getPath();
		if(path.charAt(path.length() -1) != '\\'){
			path += "\\";
		}
		loadClass(file,path);
		loadAnnotation();
	}
	
	private void loadAnnotation() throws ParserException {
		for(String className:classList){
			try {
				Method[] methods = ClazzUtil.getMethod(className);
				for(Method method:methods){
					mapperBean(method,className);
				}
			} catch (Exception e) {
				throw new ParserException(e);
			}
		}
	}
	
	protected abstract void mapperBean(Method method,String className) throws Exception;

	private void loadClass(File dir,String basePath){
		if(dir.exists()){
			if (dir.isDirectory()) {
				String[] children = dir.list();
				for (int i = 0; i < children.length; i++) {
					File direct = new File(dir, children[i]);
					loadClass(direct,basePath);
					direct = null;
				}
				children = null;
				dir = null;
			} else{
				if(dir.getName().endsWith(suff)){
					classList.add(dir.getPath().substring(basePath.length(),(dir.getPath().length() - suff.length())).replace('\\', '.'));
				}
			}
		}
	}

}
